import React, { useMemo, useEffect, useState, useRef } from 'react';
import { Table } from '@douyinfe/semi-ui';
import { SatelliteSystems } from './configs/satellite.config';
import satelliteService from '../../services/satelliteService';
import { useRealtimeContext } from './RealtimeContext';

function RealtimeTable({ satelliteType = 'BDS' }) {
    const [satelliteData, setSatelliteData] = useState([]);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const { checkedStates } = useRealtimeContext();
    const satelliteConfig = SatelliteSystems[satelliteType];

    // 额外：动态高度
    const containerRef = useRef(null);
    const [tableHeight, setTableHeight] = useState(400); // 默认值

    useEffect(() => {
        if (!containerRef.current) return;
        const observer = new ResizeObserver((entries) => {
            for (let entry of entries) {
                const { height } = entry.contentRect;
                requestAnimationFrame(() => {   // ✅ 延迟到下一帧再更新
                    setTableHeight(height);
                });
            }
        });
        observer.observe(containerRef.current);
        return () => observer.disconnect();
    }, []);

    const columns = useMemo(() => {
        return satelliteConfig.tableHeaders
            .filter(header => header.visible)
            .map(header => ({
                title: header.Label,
                dataIndex: header.id,
                key: header.id,
                width: header.width || 100,
                resizable: true,
                sorter: header.id === 'time' ? (a, b) => (a.time - b.time > 0 ? 1 : -1) : undefined,
            }));
    }, [satelliteType]);

    const checkedList = checkedStates[satelliteType] || [];
    const dataSource = useMemo(() => {
        if (!checkedList.length) {
            return satelliteData;
        }
        return satelliteData.filter(item => checkedList.includes(String(item.prn)));
    }, [satelliteData, checkedList]);

    // 加载历史数据
    useEffect(() => {
        const fetchHistoricalData = async () => {
            try {
                const response = await satelliteService.getRealtimeData(satelliteType, page, 20);
                const newData = Array.isArray(response.data?.satellites) ? response.data.satellites : [];
                setSatelliteData(prev => [...prev, ...newData]);
                setHasMore(newData.length > 0);
            } catch (error) {
                console.error('获取卫星历史数据失败:', error);
                setHasMore(false);
            }
        };
        fetchHistoricalData();
    }, [page, satelliteType]);

    // 定时获取最新数据
    useEffect(() => {
        const fetchLatestData = async () => {
            try {
                const response = await satelliteService.getRealtimeData(satelliteType, 1, 20);
                const latestData = response.data?.satellites || [];
                if (latestData.length > 0) {
                    const existingIds = new Set(satelliteData.map(item => item.id));
                    const newData = latestData.filter(item => !existingIds.has(item.id));
                    if (newData.length > 0) {
                        setSatelliteData(prev => [...newData, ...prev]);
                    }
                }
            } catch (error) {
                console.error('获取最新卫星数据失败:', error);
            }
        };
        fetchLatestData();
        const intervalId = setInterval(fetchLatestData, 5000);
        return () => clearInterval(intervalId);
    }, [satelliteType]);

    return (
        <div ref={containerRef} style={{ height: '100%', width: '100%' }}>
            <Table
                columns={columns}
                dataSource={dataSource}
                pagination={false}
                resizable={true}
                size={'small'}
                sticky={true}
                scroll={{ x: 900, y: tableHeight - 40 }} // 动态高度（40是预留表头/边距，可调）
                virtualized={{
                    itemSize: 56,
                    onScroll: ({ scrollDirection, scrollOffset, scrollUpdateWasRequested }) => {
                        if (
                            scrollDirection === 'forward' &&
                            scrollOffset >= (satelliteData.length - Math.ceil((tableHeight - 40) / 56) * 1.5) * 56 &&
                            !scrollUpdateWasRequested &&
                            hasMore
                        ) {
                            setPage(prevPage => prevPage + 1);
                        }
                    }
                }}
                style={{ minWidth: '100%', tableLayout: 'fixed' }}
            />
        </div>
    );
}

export default RealtimeTable;
